package com.imm.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imm.common.Result;
import com.imm.dto.DishDTO;
import com.imm.mapper.DishMapper;
import com.imm.pojo.Category;
import com.imm.pojo.Dish;
import com.imm.pojo.DishFlavor;
import com.imm.service.ICategoryService;
import com.imm.service.IDishFlavorService;
import com.imm.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Resource
    private IDishFlavorService dishFlavorService;

    @Resource
    private ICategoryService categoryService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<Page<DishDTO>> pageDish(int page, int pageSize, String name) {
        String pageJson = stringRedisTemplate.opsForValue().get("reggie:backend:dish:page:" + page + ":" + pageSize);
        if (StringUtils.isNotEmpty(pageJson)) {
            Page<DishDTO> pageInfo = (Page<DishDTO>) JSONUtil.toBean(pageJson, Page.class);
            return Result.success(pageInfo);
        }
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDTO> dishDTOPage = new Page<>();
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByDesc(Dish::getPrice);
        page(pageInfo, wrapper);
        // 对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDTOPage, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDTO> list = records.stream().map((item) -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            Long categoryId = item.getCategoryId();
            // 查询对象
            Category category = categoryService.getById(categoryId);
            dishDTO.setCategoryName(category.getName());
            return dishDTO;
        }).collect(Collectors.toList());
        dishDTOPage.setRecords(list);
        // 缓存进Redis
        String jsonStr = JSONUtil.toJsonStr(dishDTOPage);
        stringRedisTemplate.opsForValue().set("reggie:backend:dish:page:" + page + ":" + pageSize
                , jsonStr, 30, TimeUnit.MINUTES);
        return Result.success(dishDTOPage);
    }

    @Transactional
    @Override
    public Result<String> insert(DishDTO dishDTO) {
        save(dishDTO);
        // 同时添加口味
        Long dishId = dishDTO.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        // 删除Redis缓存
        Set<String> keys = stringRedisTemplate.keys("reggie:backend:dish:page:*");
        if (keys != null && !keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
        stringRedisTemplate.delete("redis:front:dish:list:" + dishDTO.getCategoryId() + 1);
        return Result.success("添加菜品成功");
    }

    @Override
    public Result<DishDTO> findOne(Long id) {
        Dish dish = getById(id);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(wrapper);
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish, dishDTO);
        dishDTO.setFlavors(dishFlavors);
        return Result.success(dishDTO);
    }

    @Transactional
    @Override
    public Result<String> updateOne(DishDTO dishDTO) {
        Dish dish = getById(dishDTO.getId());
        // 修改口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDTO.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        // 修改菜品
        updateById(dishDTO);
        // 删除Redis缓存
        Set<String> keys = stringRedisTemplate.keys("reggie:backend:dish:page:*");
        if (keys != null && !keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
        stringRedisTemplate.delete("redis:front:dish:list:" + dish.getCategoryId() + ":" + 1);
        return Result.success("修改成功");
    }

    @Override
    public Result<String> changeStatus(Integer status, Long ...ids) {
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        List<Long> list = List.of(ids);
        wrapper.set(Dish::getStatus, status).in(Dish::getId, list);
        update(wrapper);
        Set<String> keys = stringRedisTemplate.keys("reggie:backend:dish:page:*");
        if (keys != null && !keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
        Set<String> keysList = stringRedisTemplate.keys("reggie:front:dish:list:*");
        if (keysList != null && !keysList.isEmpty()) {
            stringRedisTemplate.delete(keysList);
        }
        return Result.success("修改状态成功成功");
    }

    @Override
    public Result<String> delete(Long[] ids) {
        List<Long> list = List.of(ids);
        removeByIds(list);
        // 删除缓存
        Set<String> keys = stringRedisTemplate.keys("reggie:backend:dish:page:*");
        if (keys != null && !keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
        }
        Set<String> keysList = stringRedisTemplate.keys("reggie:front:dish:list:*");
        if (keysList != null && !keysList.isEmpty()) {
            stringRedisTemplate.delete(keysList);
        }
        return Result.success("删除成功");
    }

    @Transactional
    @Override
    public Result<List<DishDTO>> listDish(DishDTO dishDTO) {
        // 获取缓存
        String listInfo = stringRedisTemplate.opsForValue()
                .get("reggie:front:dish:list:" + dishDTO.getCategoryId() + ":" + dishDTO.getStatus());
        if (StringUtils.isNotEmpty(listInfo)) {
            List<DishDTO> bean = JSONUtil.toList(listInfo, DishDTO.class);
            return Result.success(bean);
        }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dishDTO.getId() != null, Dish::getId, dishDTO.getId())
                .eq(Dish::getStatus, 1)
                .eq(dishDTO.getCategoryId() != null, Dish::getCategoryId, dishDTO.getCategoryId())
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = list(wrapper);
        List<DishDTO> dishDTOList = dishes.stream().map(item -> {
            DishDTO dto = new DishDTO();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dto.setCategoryName(categoryName);
            }
            // 加入口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
            dto.getFlavors().addAll(dishFlavors);
            return dto;
        }).collect(Collectors.toList());
        // 存入Redis
        String jsonStr = JSONUtil.toJsonStr(dishDTOList);
        stringRedisTemplate.opsForValue()
                .set("reggie:front:dish:list:" + dishDTO.getCategoryId() + ":" + dishDTO.getStatus()
                , jsonStr, 30, TimeUnit.MINUTES);
        return Result.success(dishDTOList);
    }
}
